package org.example.config;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.component.LoginInfo;
import org.example.component.UserInfo;
import org.example.enums.CommandEnum;
import org.example.packets.Status;
import org.example.packets.bean.Group;
import org.example.packets.bean.User;
import org.example.packets.handler.message.ChatRespBody;
import org.example.packets.handler.system.RespBody;
import org.example.packets.handler.user.GroupUser;
import org.example.packets.handler.user.UserStatusBody;
import org.example.service.UnReadMessageService;
import org.example.service.UserService;
import org.example.util.ChannelContextUtil;
import org.tio.core.ChannelContext;
import org.tio.websocket.common.WsResponse;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class Chat {

    private static final UnReadMessageService unReadMessageService = new UnReadMessageService();

    /**
     * 聊天消息
     *
     * @param chatRespBody 聊天消息体
     */
    public static void sendToGroup(ChatRespBody chatRespBody, Group group) {
        User userInfo = ImConfig.userListener().onGetUser(chatRespBody.getSenderId());
        // 构建消息体
        chatRespBody.setAvatar(userInfo.getAvatar());
        chatRespBody.setUsername(userInfo.getUsername());
        chatRespBody.setDeleted(false);

        chatRespBody.setSystem(chatRespBody.getSystem());
        if (ObjectUtil.defaultIfNull(chatRespBody.getSystem(), false)) {
            chatRespBody.setSenderId("");
        }

//      chatRespBody.setFiles(CollUtil.isEmpty(chatRespBody.getFiles()) ? null : chatRespBody.getFiles());
        // 获取到群组内的所有用户
        TimeInterval timer = DateUtil.timer();
        log.info("目标数据：" + chatRespBody.getContent());
        // 取出未读消息, 并设置未读数量

        for (GroupUser user : group.getUsers()) {
            List<ChannelContext> channelContexts = ChannelContextUtil.contextList(user.getId());

            for (ChannelContext channelContext : channelContexts) {
                LoginInfo loginInfo = new LoginInfo().setChannelContext(channelContext);
                Group userGroup = loginInfo.getGroupsMap().get(chatRespBody.getRoomId());
                userGroup.setUnreadCount(userGroup.getUnreadCount() + 1);

                chatRespBody.setUnreadCount(userGroup.getUnreadCount());
                WsResponse wsResponse = WsResponse.fromText(RespBody.success(CommandEnum.COMMAND_CHAT_REQ, chatRespBody), Im.CHARSET);
                Im.send(channelContext, wsResponse);
            }

            if (!user.getId().equals(chatRespBody.getSenderId())) {
                // 给这个用户设置未读消息
                unReadMessageService.putUnReadMessage(user.getId(), chatRespBody.getRoomId(), chatRespBody.getId(), chatRespBody.getSendTime());
            }

            // 发送给在线用户
//            List<ChannelContext> channelContexts = ChannelContextUtil.contextList(user.getId());
        }
        log.info("发送消息耗时" + timer.intervalRestart());
    }

    /**
     * 用户状态变更消息
     *
     * @param userStatusBody 用户状态消息
     */
    public static void sendToGroup(UserStatusBody userStatusBody, ChannelContext userChannel) {
        WsResponse wsResponse = WsResponse.fromText(RespBody.success(CommandEnum.COMMAND_USER_STATUS_RESP, userStatusBody), Im.CHARSET);
        Im.sendToGroup(userStatusBody.getRoomId(), wsResponse, channelContext -> !channelContext.userid.equals(userChannel.userid));
    }
    public static void sendToGroup(UserStatusBody userStatusBody) {
        WsResponse wsResponse = WsResponse.fromText(RespBody.success(CommandEnum.COMMAND_USER_STATUS_RESP, userStatusBody), Im.CHARSET);
        Im.sendToGroup(userStatusBody.getRoomId(), wsResponse);
    }


}
